import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:xiaomi/app/models/categoryModel.dart';
import 'package:xiaomi/app/models/hotSellModel.dart';
import 'package:xiaomi/app/models/swiperModel.dart';

class HomeController extends GetxController {
  //TODO: Implement HomeController

  final ScrollController scrollController = ScrollController();

  RxDouble appBarAlpha = 0.0.obs;

  /// listview偏移的距离
  double padingOffset = -60;

  /// 轮播图数据源
  RxList<SwiperModelItem> swiperData = <SwiperModelItem>[].obs;

  ///首页种类列表
  RxList<CategoryItemModel> categoryData = <CategoryItemModel>[].obs;

  /// 热门甄选板块轮播图
  RxList<SwiperModelItem> swiperData2 = <SwiperModelItem>[].obs;

  /// 热门甄选右侧
  RxList<HotSellItemModel> hotSellData = <HotSellItemModel>[].obs;

  /// 热门甄选下方的瀑布流数据
  RxList<HotSellItemModel> goodSellData = <HotSellItemModel>[].obs;

  @override
  void onInit() {
    super.onInit();

    /// 获取数据
    _getSwiperData();
    _getCategoryData();
    _getSwiperData2();
    _getHotSellData();
    _getGoodSellData();

    scrollController.addListener(() {
      // scrollController.position
      var alpha = scrollController.position.pixels / -padingOffset;
      if (alpha < 0) {
        appBarAlpha.value = 0;
      } else if (alpha > 1) {
        appBarAlpha.value = 1;
      } else {
        appBarAlpha.value = alpha;
      }

      update();
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();

    scrollController.dispose();
  }

  void _getSwiperData() async {
    var rsp = await Dio().get('https://miapp.itying.com/api/focus');
    swiperData.value = SwiperModel.fromJson(rsp.data).result!;
    update();
  }

  void _getCategoryData() async {
    var catersp = await Dio().get('https://miapp.itying.com/api/bestCate');
    categoryData.value = CategoryModel.fromJson(catersp.data).result!;
    update();
  }

  void _getSwiperData2() async {
    var rsp = await Dio().get('https://miapp.itying.com/api/focus?position=2');
    swiperData2.value = SwiperModel.fromJson(rsp.data).result!;
    update();
  }

  void _getHotSellData() async {
    var rsp = await Dio().get('http://miapp.itying.com/api/plist?is_hot=1');
    hotSellData.value = HotSellModel.fromJson(rsp.data).result!;
    update();
  }

  void _getGoodSellData() async {
    var rsp = await Dio().get('https://miapp.itying.com/api/plist?is_best=1');
    goodSellData.value = HotSellModel.fromJson(rsp.data).result!;
    update();
  }
}
